package com.zzyl.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zzyl.base.PageResponse;
import com.zzyl.constant.SuperConstant;
import com.zzyl.dto.RoleDto;
import com.zzyl.entity.Role;
import com.zzyl.entity.RoleResource;
import com.zzyl.enums.BasicEnum;
import com.zzyl.exception.BaseException;
import com.zzyl.mapper.RoleMapper;
import com.zzyl.mapper.RoleResourceMapper;
import com.zzyl.mapper.UserRoleMapper;
import com.zzyl.service.RoleService;
import com.zzyl.vo.RoleVo;
import org.assertj.core.util.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class RoleServiceImpl implements RoleService {

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private RoleResourceMapper roleResourceMapper;

    @Autowired
    private UserRoleMapper userRoleMapper;

    /**
     * 分页擦好像
     *
     * @param roleDto  查询条件
     * @param pageNum  当前页
     * @param pageSize 每页显示记录数
     * @return
     */
    @Override
    public PageResponse<RoleVo> list(RoleDto roleDto, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);

        Page<Role> page = roleMapper.list(roleDto.getRoleName());
        return PageResponse.of(page, RoleVo.class);
    }

    /**
     * 新增角色
     *
     * @param roleDto
     * @return
     */
    @Override
    public Boolean add(RoleDto roleDto) {
        Role role = BeanUtil.toBean(roleDto, Role.class);
        role.setUpdateTime(LocalDateTime.now());
        role.setCreateTime(LocalDateTime.now());
        role.setRemark(roleDto.getRoleName());
        role.setCreateBy(1671403256519078006L);

        return roleMapper.insert(role);
    }

    /**
     * 4.3 根据角色查询选中的资源数据
     *
     * @param roleId
     * @return
     */
    @Override
    public List<String> findCheckedResources(Long roleId) {
        return roleResourceMapper.findCheckedResources(roleId);
    }

    /**
     * 删除角色
     *
     * @param roleIds
     */
    @Override
    @Transactional
    public void delete(String roleIds) {
        //1. 通过id查询角色信息 然后判断状态 如果是已禁用则进行删除 如果不是则报错
       Role role =  roleMapper.selectById(roleIds);
       if(null != role && SuperConstant.DATA_STATE_0.equals(role.getDataState())){
           throw new BaseException(BasicEnum.PARENT_ROLE_STATUS);
       }

        //2. 删除角色和资源的关系数据
        roleResourceMapper.deleteByRoleId(roleIds);

        //3. 删除角色数据
        roleMapper.delete(roleIds);
    }

    /**
     * 角色的更新
     *
     * @param roleDto
     * @return
     */
    @Override
    public Boolean update(RoleDto roleDto) throws CloneNotSupportedException {
//        Role role = BeanUtil.toBean(roleDto, Role.class);
        Role role = roleDto.clone();
        role.setUpdateTime(LocalDateTime.now());
        role.setUpdateBy(1671403256519078138L);


        //状态的修改-如果是修改为禁用 那么需要查询当前角色下是否有用户
        if(null != roleDto && SuperConstant.DATA_STATE_1.equals(roleDto.getDataState())){
            Integer count = userRoleMapper.countByRoleId(roleDto.getId());
            if(null != count && count > 0){
                throw new BaseException(BasicEnum.ROLE_DISTRIBUTED);
            }
        }

        Boolean flag = roleMapper.update(role);

        // 重新构建角色和资源之间的关系  先删除 然后判断前端是否传递了资源数据 如果有则批量新增 如果没有则返回
        roleResourceMapper.deleteByRoleId(roleDto.getId() + "");
        if(ObjectUtil.isEmpty(roleDto.getCheckedResourceNos())){
            //如果为空
            return flag;
        }

        List<RoleResource> roleResourceList = Lists.newArrayList();
        Arrays.asList(roleDto.getCheckedResourceNos()).stream().map(no -> {
            RoleResource roleResource = new RoleResource();
            roleResource.setRoleId(roleDto.getId());
            roleResource.setResourceNo(no);
            roleResource.setCreateTime(LocalDateTime.now());
            roleResource.setUpdateTime(LocalDateTime.now());
            roleResource.setDataState(SuperConstant.DATA_STATE_0);

            roleResourceList.add(roleResource);
            return roleResource;
        }).collect(Collectors.toList());

        roleResourceMapper.batchInsert(roleResourceList);

        return flag;
    }
}
